#include "adLogic.h"
#include "adDao.h"
#include "glib.h"
#include "gio/gio.h"
#include "curlResquest.h"

#define RES_PATH "/home/heron/ronghuanet_ads/medias/"


Ad* parseUpDownSplitScr(cJSON *adJson)
{
    Ad * result = calloc(1,sizeof(Ad));
    if (cJSON_IsObject(adJson))
    {
        //自己的一些属性解析
        cJSON *idJson = cJSON_GetObjectItemCaseSensitive(adJson,"id");
        int id = idJson->valueint;
        cJSON *templateIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"template_id");
        int templateId = templateIdJson->valueint;
        cJSON *customerIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"customer_id");
        int customerId = customerIdJson->valueint;
        cJSON *startTimeJson = cJSON_GetObjectItemCaseSensitive(adJson,"start_time");
        char *startTime = startTimeJson->valuestring;
        cJSON *endTimeJson = cJSON_GetObjectItemCaseSensitive(adJson,"end_time");
        char *endTime = endTimeJson->valuestring;
        result->id  = id;
        result->template_id  = templateId;
        result->customer_id  = customerId;
        result->start_time  = startTime;
        result->end_time  = endTime;
        //AdResource *resources[3];

        //广告资源解析
        AdResource *upAr = calloc(1,sizeof(AdResource));
        upAr->ad_id = id;
        upAr->index = 0;
        cJSON *typeIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_type_id");
        int typeId = typeIdJson->valueint;
        upAr->type_id = typeId;
        cJSON *urlJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_url");
        char *url = urlJson->valuestring;
        upAr->path = url;
        cJSON *signJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_sign");
        char *sign = signJson->valuestring;
        upAr->sign = sign;

        result->adResources[0] =upAr;

        AdResource *buttomAr = calloc(1,sizeof(AdResource));
        buttomAr->ad_id = id;
        buttomAr->index = 0;
        cJSON *typeIdJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_type_id");
        int typeId1 = typeIdJson1->valueint;
        buttomAr->type_id = typeId1;
        cJSON *urlJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_url");
        char *url1 = urlJson1->valuestring;
        buttomAr->path = url1;
        cJSON *signJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_sign");
        char *sign1 = signJson1->valuestring;
        buttomAr->sign = sign1;

        result->adResources[1] =buttomAr;
        result->adResources[2]=NULL;
    }
    return result;
}

char *getResPath(AdResource *ar)
{
    //获取广告的id
    int ad_id = ar->ad_id;
    //获取文件的文件名
    gchar *file_name = g_path_get_basename(ar->path);
    //规定格式
    char *str = "%s/%d_%s";

    return g_strdup_printf(str, RES_PATH, ad_id, file_name);
}

int downloadAdsToSqlite(Ad *ads[], int size)
{
    //声明数据标识 --> 决定是否需要更新
    int flag = 0;
    //遍历ads
    for (int i = 0; i < size; i++)
    {
        //获取id
        Ad *ad = ads[i];
        int ad_id = ad->id;
        //数据库查询该数据是否存在
        Ad *adInDb = getByIdAd(ad_id);
        //判断做不同的操作
        if (adInDb == NULL)
        {
            //不存在
            flag = 1;
            //将Ad保存到数据库
            insertAd(ad);
            //媒体文件的处理 --> 3是规定死的 --> 且第三个是null
            for (int j = 0; j < 3; j++)
            {
                AdResource *ar = ad->adResources[j];
                if (ar != NULL)
                {
                    char *local_ar_path = getResPath(ar);
                    //判断是否存在
                    gboolean exits = g_file_test(local_ar_path, G_FILE_TEST_EXISTS);
                    if (!exits)
                    {
                        //创建文件
                        GFile *file = g_file_new_for_path(local_ar_path);
                        if (!g_file_create(file, 0, NULL, NULL))
                        {
                            printf("create file error!");
                        }
                    }
                    //下载文件
                    downloadRes(ar->path, local_ar_path);
                    //替换ar->path
                    ar->path = local_ar_path;
                    //保存到数据库
                    insertAr(ar);
                }
            }
        }else
        {
            //广告在数据库中存在
            //更新广告
            updateAd(ad);
            //检查需要下载媒体资源否
            for (int j = 0; j < 3; j++)
            {
                AdResource *ar = ad->adResources[j];
                if (ar != NULL)
                {
                    char *local_ar_path = getResPath(ar);
                    //远程加密串
                    char *sn = ar->sign;
                    //获取本地加密的串
                    char *local_sn = "jfjjfjfjj";
                    if (!g_str_equal(sn, local_sn))
                    {
                        //判断文件是否存在
                        gboolean exits = g_file_test(local_ar_path, G_FILE_TEST_EXISTS);
                        if (!exits)
                        {
                            flag = 1;
                            //创建文件
                            GFile *file = g_file_new_for_path(local_ar_path);
                            if (!g_file_create(file, 0, NULL, NULL))
                            {
                                printf("create file error!");
                            }
                        }
                        //下载文件
                        downloadRes(ar->path, local_ar_path);
                        //替换路径
                        ar->path = local_ar_path;
                        //保存到数据库
                        insertAr(ar);
                    }
                }  
            }
        }
    }
}

void handleAdList(cJSON* adListArray)
{
    //判断参数是不是一个数组
    if (!cJSON_IsArray(adListArray))
    {
        return;
    }

    //获取数组长度 --> 遍历需要
    int size = cJSON_GetArraySize(adListArray);
    //准备一个数组 --> 用于接收数据
    Ad *ads[size];
    //遍历
    for (int  i = 0; i < size; i++)
    {
        //获取第几个对象
        cJSON *addJsonStr = cJSON_GetArrayItem(adListArray, i);
        //获取模板类型 --> 决定流媒体怎么呈现
        int templateId = cJSON_GetObjectItemCaseSensitive(adListArray, "template_id");
        //判断是属于那种排版
        switch (templateId)
        {
        case 6: //上下分屏
            Ad *ad = parseUpDownSplitScr(adListArray);
            break;
        
        case 5:
            break;
        
        default:
            g_print("template_id 非法！\n");
            break;
        }
    }
    //把数据存储到数据库并进行资源同步
    int res = downloadAdsToSqlite(ads, size);

    //释放资源
    for (int i = 0; i < size; i++)
    {
        Ad *ad =  ads[i];
        g_print("adid=%d\n",ad->id);
        for (int i = 0; i < 3; i++)
        {
            AdResource *ar = ad->adResources[i];
            if (ar!=NULL)
            {
                g_print("url=%s\n",ar->path);
                free(ar);
            }
        }
        free(ad);
    }


    //5.如果资源/广告列表有更新变化，qt进程重新加载内容
    if (res==1)
    {
        //进程间的通讯  --> QT进程发送消息策略
    }else
    {
        //播放最新的广告即可
    }
}